package com.ruoyi.system.service.aggregation.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.common.utils.sms.AliyunSmsUtils;
import com.ruoyi.system.service.aggregation.ISmsService;
import java.util.concurrent.TimeUnit;

/**
 * 短信服务实现类
 * 
 * @author ruoyi
 * @date 2025-01-01
 */
@Service
public class SmsServiceImpl implements ISmsService
{
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AliyunSmsUtils aliyunSmsUtils;

    private static final String SMS_CODE_PREFIX = "sms:code:";
    private static final int CODE_EXPIRE_TIME = 5; // 5分钟过期

    /**
     * 发送短信验证码
     */
    @Override
    public boolean sendCode(String phone)
    {
        try
        {
            // 防止60秒内重复发送
            String lockKey = SMS_CODE_PREFIX + "lock:" + phone;
            Boolean hasLock = redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 60, TimeUnit.SECONDS);
            if (hasLock == null || !hasLock)
            {
                throw new RuntimeException("请勿频繁发送验证码，请60秒后再试");
            }

            // 生成6位随机验证码
            String code = aliyunSmsUtils.generateVerifyCode();
            
            // 存入Redis，5分钟过期
            String key = SMS_CODE_PREFIX + phone;
            redisTemplate.opsForValue().set(key, code, CODE_EXPIRE_TIME, TimeUnit.MINUTES);
            
            // 调用阿里云短信服务发送验证码
            boolean success = aliyunSmsUtils.sendVerifyCode(phone, code);
            
            if (!success)
            {
                // 发送失败，删除锁和验证码
                redisTemplate.delete(lockKey);
                redisTemplate.delete(key);
            }
            
            return success;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 验证短信验证码
     */
    @Override
    public boolean verifyCode(String phone, String code)
    {
        String key = SMS_CODE_PREFIX + phone;
        String cachedCode = redisTemplate.opsForValue().get(key);
        
        if (cachedCode != null && cachedCode.equals(code))
        {
            // 验证成功后删除验证码
            redisTemplate.delete(key);
            return true;
        }
        
        return false;
    }

}

